/**
 * Description: 请求类封装
 *
 * Created by hrx on 2023/9/18
 */
import axios,
{
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type AxiosError,
  type CreateAxiosDefaults,
  type CancelTokenSource,
  type InternalAxiosRequestConfig
}
  from "axios";
import {ElMessage} from "element-plus";
import {startLoading, endLoading} from "./loading";
import {getLocal} from "./local";
import route from '@/router';

const base_url = import.meta.env.VITE_BASE_URL

// 回复数据接口类型
export interface IResponseDto<T = any> {
  data: T;
  msg: string;
  code: number;
}

export interface IResponseArrayDto<T> {
  list: Array<T>;
  currPage: number;
  pageSize: number;
  totalCount: number;
  totalPage: number;
}

// 初始化axios的配置接口类型
export interface IBaseConfig extends CreateAxiosDefaults {
  onError?: (error: AxiosError) => void;
  onLoading?: (res: boolean) => void;
  showDefaultErrorMsg?: boolean;
}


// 请求的配置接口类型
export interface IRequestConfig extends AxiosRequestConfig {
  showLoading?: boolean;
}

// 请求拦截接口类型
export interface IInternalRequestConfig extends InternalAxiosRequestConfig {
  showLoading?: boolean;
}

// 回复接口类型
export interface IResponse extends AxiosResponse<IResponseDto> {
  config: IInternalRequestConfig;
}

const service = axios.create({
  baseURL: base_url,
  timeout: 30000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
    "showLoading": false
  }
})

service.interceptors.request.use((config: IInternalRequestConfig) => {
  if (config.headers.showLoading) startLoading();
  config.headers = config.headers || {}
  const token = getLocal('token');
  if (token) {
    config.headers.set('Authorization', token);
    config.headers.set('merchantCode', 1);
  }
  return config
})

service.interceptors.response.use(
  (response: IResponse) => {
  if (response.config.headers.showLoading) endLoading();
  return new Promise((resolve, reject) => {
    const code: number = response.data.code
    if(code == 200 || code == 0){
      resolve(response)
      return ;
    }
    if (code == 401) {
      route.push('/login');
      ElMessage.error(response.data.msg)
      reject(response)
      return;
    }
    if(response.request.responseType == 'blob') {
      resolve(response)
      return ;
    }
    ElMessage.error(response.data.msg)
    resolve(response)
  })
}, error => {
    endLoading();
    ElMessage.error('系统不舒服了！')
})

export default service